package com.dhecp.project.api.service.impl;

import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.*;
import com.bo.sellingpartnerapi.Catalogitems20220401.api.CatalogApi;
import com.bo.sellingpartnerapi.Fbainventory.api.FbaInventoryApi;
import com.bo.sellingpartnerapi.Fbainventory.model.GetInventorySummariesResponse;
import com.bo.sellingpartnerapi.Fbainventory.model.InventorySummary;
import com.bo.sellingpartnerapi.Fbainventory.model.Pagination;
import com.bo.sellingpartnerapi.Feeds20210630.model.Feed;
import com.bo.sellingpartnerapi.Listingsitems20210801.api.ListingsApi;
import com.bo.sellingpartnerapi.Listingsitems20210801.model.Item;
import com.bo.sellingpartnerapi.Listingsitems20210801.model.ItemSummaryByMarketplace;
import com.bo.sellingpartnerapi.Ordersv0.api.OrdersV0Api;
import com.bo.sellingpartnerapi.Ordersv0.model.GetOrderItemsResponse;
import com.bo.sellingpartnerapi.Ordersv0.model.GetOrdersResponse;
import com.bo.sellingpartnerapi.Ordersv0.model.Order;
import com.bo.sellingpartnerapi.Ordersv0.model.OrderItem;
import com.bo.sellingpartnerapi.Reports20210630.api.ReportsApi;
import com.bo.sellingpartnerapi.Reports20210630.model.*;
import com.dhecp.common.config.Global;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.utils.DateUtil;
import com.dhecp.core.utils.DateUtils;
import com.dhecp.core.utils.MathExtUtils;
import com.dhecp.project.api.api.FbaInboundApi;
import com.dhecp.project.api.client.model.SellerSecretsVO;
import com.dhecp.project.api.domain.*;
import com.dhecp.project.api.enums.*;
import com.dhecp.project.api.mapper.AmazonShopExchangeRateMapper;
import com.dhecp.project.api.mapper.AmazonShopMapper;
import com.dhecp.project.api.mapper.AmazonShopOrderMapper;
import com.dhecp.project.api.mapper.AmazonShopProductMapper;
import com.dhecp.project.api.service.ApiAmazonService;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.service.DataExecutionService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.api.util.ApiHttpUtils;
import com.dhecp.project.api.util.Helper;
import com.squareup.okhttp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;

import javax.xml.crypto.Data;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRules;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;

/**
 * @ClassName ApiAmazonServiceImpl
 * @Description TODO
 * @Author alula
 * @Date 2022-09-23 19:24
 */
@Service
public class ApiAmazonServiceImpl implements ApiAmazonService {

    private static final Logger logger = LoggerFactory.getLogger(ApiAmazonServiceImpl.class);

    @Autowired
    private AmazonShopMapper amazonShopMapper;

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private AmazonShopOrderMapper amazonShopOrderMapper;

    @Autowired
    private AmazonShopProductMapper amazonShopProductMapper;

    @Autowired
    private AmazonShopExchangeRateMapper amazonShopExchangeRateMapper;

    @Autowired
    private DataExecutionService dataExecutionService;

    /**
     * 创建亚马逝销售渠道MAP
     * @return
     */
    private Map<String, Object> getAmazonSalesChannelMap(){
        Map<String, Object> amazonSalesChannelMap = new HashMap<>();
        amazonSalesChannelMap.put("Amazon.ca", "CA");
        amazonSalesChannelMap.put("Amazon.co.jp", "JP");
        amazonSalesChannelMap.put("Amazon.co.uk", "GB");
        amazonSalesChannelMap.put("Amazon.com", "US");
        amazonSalesChannelMap.put("Amazon.de", "DE");
        amazonSalesChannelMap.put("Amazon.es", "ES");
        amazonSalesChannelMap.put("Amazon.fr", "FR");
        amazonSalesChannelMap.put("Amazon.it", "IT");
        amazonSalesChannelMap.put("Amazon.nl", "NL");
        amazonSalesChannelMap.put("Amazon.pl", "PL");
        amazonSalesChannelMap.put("Amazon.se", "SE");
        amazonSalesChannelMap.put("Amazon.com.mx", "MX");
        amazonSalesChannelMap.put("Amazon.com.tr", "TR");
        amazonSalesChannelMap.put("Amazon.cn", "CN");
        amazonSalesChannelMap.put("Amazon.br", "BR");
        amazonSalesChannelMap.put("Amazon.com.br", "BR");
        amazonSalesChannelMap.put("Amazon.in", "IN");
        amazonSalesChannelMap.put("Amazon.sa", "SA");
        amazonSalesChannelMap.put("Amazon.ae", "AE");
        amazonSalesChannelMap.put("Amazon.eg", "EG");
        amazonSalesChannelMap.put("Amazon.sg", "SG");
        amazonSalesChannelMap.put("Amazon.au", "AU");
        amazonSalesChannelMap.put("Amazon.com.au", "AU");
        amazonSalesChannelMap.put("Amazon.com.be", "BE");
        amazonSalesChannelMap.put("SI CA Prod Marketplace", "CA");
        amazonSalesChannelMap.put("SI Prod ES Marketplace", "ES");
        amazonSalesChannelMap.put("SI Prod IT Marketplace", "IT");
        amazonSalesChannelMap.put("SI UK Prod Marketplace", "GB");
        return  amazonSalesChannelMap;
    }

    public static Map<String, Integer> THREAD_MAP = new HashMap<String, Integer>(){{
        for (int i = 0; i < 70; i++) {
            put("thread"+i, 0);
        }
    }};

    @Override
    //@Transactional(timeout=1000,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse getAllAmazonOrderInfo(int insertLogId, String system, String type, Map<String, Object> queryParams, Date startTime,Integer genre, Date endTime) {
        ApiResponse apiResponse = new ApiResponse();
        for (Entry<String, Integer> e : THREAD_MAP.entrySet()) {
            if (e.getValue() == 1) {
                logger.info("短时间内不允许操作");
                apiResponse.setCode(300);
                return apiResponse;
            }
        }
        StringBuilder messageBuilder = new StringBuilder();
        Date nowDate = new Date();
        nowDate.setHours(0);
        nowDate.setMinutes(0);
        nowDate.setSeconds(0);
        try {
            List<AmazonShop> amazonShopList = amazonShopMapper.findGroupAmazonShopList(queryParams);
            List<AmazonShopExchangeRate> findAmazonShopExchangeRate = amazonShopExchangeRateMapper.findAmazonShopExchangeRate();
            if (amazonShopList != null && amazonShopList.size() >0){
                for (AmazonShop item:amazonShopList) {
                    boolean variable = true;
                    while (variable) {
                        for (Entry<String, Integer> e : THREAD_MAP.entrySet()) {
                            if (e.getValue() == 1) {
                                continue;
                            } else if (e.getValue() == 0) {
                                THREAD_MAP.put(e.getKey(), 1);
                                // 开启线程
                                Thread t = new Thread(() -> {
                                    logger.info("开始线程"+item.getShopName());
                                    if (!StringUtils.isEmpty(item.getRefreshToken()) && !StringUtils.isEmpty(item.getRegionCode())) {
                                        //测试时指定一个店铺用SILULCM-GB,SILULCM-ES
                                        //if (!item.getShopUser().equals("yelingdian -GB") && !item.getShopUser().equals("TESX-GB")){
                                        //continue;
                                        //}
                                        //获取不到区域对应的端点枚举，直接跳转过
                                        RegionEnum regionEnum = RegionEnum.from(item.getRegionCode().toUpperCase());
                                        if (regionEnum != null) {
                                            List<AmazonShopOrder> amazonShopOrderList = new ArrayList<>();
                                            List<String> amazonOrderNoList = new ArrayList<>();
                                            //String methodResult = getAmazonShopOrderBySpApi(system, type, ordersApi, item, "", amazonShopOrderList, amazonOrderNoList, batchNo);
                                            String methodResult = getAmazonShopOrderByReport(system, type, item, amazonShopOrderList, amazonOrderNoList, startTime, findAmazonShopExchangeRate,endTime);
                                            //保存一个店铺所有区域获取的订单信息
                                            try {
                                                if (amazonShopOrderList.size() > 0) {
                                                    //先删除原来的旧数据
                                                    Map<String, Object> deleteMap = new HashMap<>();
                                                    int deleteLength = amazonShopOrderList.size();
                                                    int j = 0;
                                                    while (deleteLength > 90) {
//                                                        deleteMap.put("ids", amazonOrderNoList.subList(j, j + 90));
                                                        amazonShopOrderMapper.deleteAmazonShopOrderByMap(amazonShopOrderList.subList(j, j + 90));
                                                        j = j + 90;
                                                        deleteLength = deleteLength - 90;
                                                    }
                                                    if (deleteLength > 0) {
//                                                        deleteMap.put("ids", amazonOrderNoList.subList(j, j + deleteLength));
                                                        amazonShopOrderMapper.deleteAmazonShopOrderByMap(amazonShopOrderList.subList(j, j + deleteLength));
                                                    }
                                                    int insertLength = amazonShopOrderList.size();
                                                    int i = 0;
                                                    while (insertLength > 90) {
                                                        amazonShopOrderMapper.insertAmazonShopOrderBatch(amazonShopOrderList.subList(i, i + 90));
                                                        i = i + 90;
                                                        insertLength = insertLength - 90;
                                                    }
                                                    if (insertLength > 0) {
                                                        amazonShopOrderMapper.insertAmazonShopOrderBatch(amazonShopOrderList.subList(i, i + insertLength));
                                                    }
                                                }
                                                if (!StringUtils.isEmpty(methodResult)) {
                                                    messageBuilder.append(methodResult);
                                                } else {
                                                    //获取没错，更新下一次获取订单的时间
                                                    Map<String, Object> updateShopMap = new HashMap<>();
                                                    updateShopMap.put("guid", item.getGuid());
                                                    updateShopMap.put("lastOrderSyncDate", DateUtil.getYYYY_MM_DD_HH_mm_ss(new Date()));
                                                    amazonShopMapper.updateByLastOrderSyncDate(updateShopMap);
                                                }
                                            } catch (Exception ex) {
                                                THREAD_MAP.put(e.getKey(), 0);
                                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ item.getShopUser()  + "-" + item.getShopName() + "]订单order报表信息", "",400, "ECP_API调用获取亚马逊单个店铺["+ item.getShopUser()  + "-" + item.getShopName() + "]订单order报表信息出错，错误信息为：" + ex.getMessage());
                                            }
                                        }
                                    }
                                    THREAD_MAP.put(e.getKey(), 0);
                                });
                                t.start();
                                Thread.sleep(1000L);
                            }
                            variable = false;
                            break;
                        }
                    }
                }
                if (!StringUtils.isEmpty(messageBuilder.toString())){
                    apiResponse.setMessage("获取店铺亚马逊订单成功！，其中失败的如下：\n\r" + messageBuilder.toString());
                }else{
                    apiResponse.setMessage("获取店铺亚马逊订单成功！");
                }
            }else {
                apiResponse.setMessage("运营商名下店铺信息为空，不获取订单信息！");
            }
            Map<String, Object> params = new HashMap<String, Object>();
            Map<String, Object> param2 = new HashMap<String, Object>();
            Date date = new Date();
            if(genre == 1){
                params.put("paymentTime",String.valueOf(queryParams.get("paymentTime")));
                params.put("type","成功");
                params.put("updateTime",date);
                dataExecutionService.updateDataExecution(params);
            } else if(genre == 2){
                //前一天
                Calendar calendar = new GregorianCalendar();
                calendar.add(Calendar.DATE, -1);

                //前14天
                Calendar calen = new GregorianCalendar();
                calen.add(Calendar.DATE, -14);
                //将14天前的数据时间修改
                param2.put("paymentTime",calen.getTime());
                param2.put("updateTime",date);
                dataExecutionService.updateDataExecutionTwo(param2);

                //新增
                SimpleDateFormat ceshiFmt2 =new SimpleDateFormat("yyyy-MM-dd");
                params.put("guid",UUID.randomUUID().toString().toUpperCase());
                params.put("type","成功");
                params.put("createTime",date);
                params.put("updateTime",date);
                params.put("paymentTime",calendar.getTime());
                params.put("currentDay",ceshiFmt2.format(calendar.getTime()));
                List<DataExecution> dataExecutions = dataExecutionService.queryDataExecutionList(params);
                if (dataExecutions.size() == 0){
                    dataExecutionService.addDataExecution(params);
                }
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiLogService.updateApiLog(insertLogId, system, type, "queryParams："+JSON.toJSONString(queryParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取亚马逊订单接口出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API调用获取亚马逊订单接口出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }
    /**
     * 保存一个店铺的订单报表信息
     * @param system
     * @param type
     * @param amazonShop
     * @return
     */
    protected String getAmazonShopOrderByReport(String system, String type, AmazonShop amazonShop, List<AmazonShopOrder> amazonShopOrderList, List<String> amazonOrderNoList, Date startTime, List<AmazonShopExchangeRate> amazonShopExchangeRateList, Date endTime){
        long start=System.currentTimeMillis();
        int insertLogId = 0;
        Date nowDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = simpleDateFormat.format(nowDate);
        String startTimeStr = DateUtils.convertDateToTDate(startTime);//amazonShop.getLastOrderSyncDate();(2023.01.29以各个调用方法时传的开始时间为准)
        String endTimeStr = DateUtils.convertDateToTDate(endTime);
        String errorMsg = "";
        String result = "";
        List<String> marketplaceIdList =  new ArrayList<>();
        if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
            String marketplaceIds = amazonShop.getMarketplaceIds();
            String[] marketplaceIdArray = marketplaceIds.split(",");
            marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
        }
        CreateReportSpecification body = new CreateReportSpecification();
        body.setReportType("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL");
        body.setMarketplaceIds(marketplaceIdList);
        body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
        body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
        ReportOptions reportOptions = new ReportOptions();
        reportOptions.put("custom", "true");
        body.setReportOptions(reportOptions);
        AmazonShopOrder amazonShopOrder = null;
        try {
            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());
            if (regionEnum == null){
                result = "店铺绑定的区域对应端点枚举获取不到，请检查！";
                return  result;
            }

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi reportsApi = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();

            CreateReportResponse reportResponse =  null;
            insertLogId = apiLogService.addApiLog(system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), "", 0, "");
            try {
                reportResponse = reportsApi.createReport(body);
                if (reportResponse != null){
                    String reportId = reportResponse.getReportId();
                    String reportDocumentId = "";
                    Report report = null;
                    Report.ProcessingStatusEnum processingStatus = null;
                    while (true){
                        report = reportsApi.getReport(reportId);
                        processingStatus = report.getProcessingStatus();
                        if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
                            if (report != null) {
                                reportDocumentId = report.getReportDocumentId();
                            }
                            break;
                        }else {
                            Thread.sleep(10000L);
                            continue;
                        }
                    }
                    if (report != null){
                        if (!StringUtils.isEmpty(reportDocumentId)) {
                            ReportDocument reportDocument = reportsApi.getReportDocument(reportDocumentId);
                            if (reportDocument != null) {
                                String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
                                OkHttpClient httpclient = new OkHttpClient();
                                Request request = new Request.Builder()
                                        .url(reportDocument.getUrl())
                                        .get()
                                        .build();

                                Response httpResponse = httpclient.newCall(request).execute();
                                if (!httpResponse.isSuccessful()) {
                                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
                                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message());
                                    return result;
                                }
                                try (ResponseBody responseBody = httpResponse.body()) {
                                    MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                                    Charset charset = mediaType.charset();
                                    if (charset == null) {
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString();
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString());
                                        return result;
                                    }
                                    Closeable closeThis = null;
                                    try {
                                        InputStream inputStream = responseBody.byteStream();
                                        closeThis = inputStream;
                                        if ("GZIP".equals(compressionAlgorithm)) {
                                            inputStream = new GZIPInputStream(inputStream);
                                            closeThis = inputStream;
                                        }
                                        if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                                            closeThis = inputStreamReader;
                                            BufferedReader reader = new BufferedReader(inputStreamReader);
                                            closeThis = reader;
                                            StringBuilder stringBuilder = new StringBuilder();
                                            String line ;
                                            do {
                                                line = reader.readLine();
                                                if (line != null) {
                                                    stringBuilder.append(line);
                                                    stringBuilder.append("\n");
                                                }
                                            } while (line != null);
                                            String filePath = Global.getProfile() + "/amazonreport/order/"+nowDateStr.replace("-", "");
                                            String fileName = "order_report_" + amazonShop.getGuid() +".cvs";
                                            File file = new File(filePath);
                                            if(!file.exists()){
                                                file.mkdirs();
                                            }
                                            File reportFile = new File(filePath + "/"+ fileName);
                                            if (!reportFile.exists()){
                                                reportFile.createNewFile();
                                            }
                                            OutputStream outputStream = new FileOutputStream(reportFile);
                                            outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                                            outputStream.close();
                                            BufferedReader csvBufferedReader = null;
                                            String reportLine = "";
                                            String separator = "\t";
                                            try {
                                                InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/"+ fileName), StandardCharsets.UTF_8);
                                                csvBufferedReader = new BufferedReader(csvInputStreamReader);
                                                String title = csvBufferedReader.readLine();
                                                if ("Date range exceeded. Report can be requested only upto 30 days".equals(title)){
                                                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+title;
                                                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时，具体错误为："+title);
                                                }
                                                String[] titleSplit = title.split(separator);
                                                while ((reportLine = csvBufferedReader.readLine()) != null) {
                                                    if (!StringUtils.isEmpty(reportLine)) {
                                                        //内容数组
                                                        String[] reportArray = reportLine.split(separator);
                                                        //判断内容和标题的size
                                                        if ((reportArray.length) < titleSplit.length) {
                                                            int len = titleSplit.length - reportArray.length;
                                                            reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
                                                        }
                                                        String amazonOrderId = "";
                                                        String purchaseDate = "";
                                                        String lastUpdateDate = "";
                                                        String orderStatus = "";
                                                        String salesChannel = "";
                                                        String quantity = "";
                                                        String sellerSku = "";
                                                        String asin = "";
                                                        String currency = "";
                                                        String orderMoney = "";
                                                        String itemTax = "";
                                                        for (int i = 0; i < titleSplit.length; i++) {
                                                            if (titleSplit[i].equals(OrderStatusType.T_AMAZONORDERID.getCode())){
                                                                amazonOrderId = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_PURCHASEDATE.getCode())){
                                                                purchaseDate = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_LASTUPDATEDDATE.getCode())){
                                                                lastUpdateDate = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_ORDERSTATUS.getCode())) {
                                                                orderStatus = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_SALESCHANNEL.getCode())) {
                                                                salesChannel = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_SELLERSKU.getCode())) {
                                                                sellerSku = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_ASIN.getCode())) {
                                                                asin = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_QUANTITY.getCode())) {
                                                                quantity = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_CURRENCY.getCode())) {
                                                                currency = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_ORDERMONEY.getCode())) {
                                                                orderMoney = reportArray[i];
                                                            }
                                                            if (titleSplit[i].equals(OrderStatusType.T_ITEMTAX.getCode())) {
                                                                itemTax = reportArray[i];
                                                            }
                                                        }
                                                        Map<String, Object> amazonSalesChannelMap = getAmazonSalesChannelMap();
                                                        String dataCountryCode = "";
                                                        if (amazonSalesChannelMap.containsKey(salesChannel)){
                                                            dataCountryCode = (String) amazonSalesChannelMap.get(salesChannel);
                                                        }
                                                        //判断销售渠道对应的国家代码不一至时，此数据不属于本店铺，直接跳过
//                                                        if (!dataCountryCode.toLowerCase().equals(amazonShop.getRegionCountryCode().toLowerCase())){
//                                                            continue;
//                                                        }
                                                        Double exchangeRate1 = 0d;
                                                        Double exchangeRate2 = 0d;
                                                        if (amazonShopExchangeRateList.size() != 0) {//根据currency汇率代码去取相应的公司汇率与官方汇率
                                                            String finalCurrency = currency;
                                                            List<AmazonShopExchangeRate> amazonShopExchangeRates =
                                                                    amazonShopExchangeRateList.stream().filter(
                                                                            amazonShopExchangeRate -> amazonShopExchangeRate.getCode().equals(finalCurrency))
                                                                            .collect(Collectors.toList());
                                                            if (amazonShopExchangeRates.size() != 0){
                                                                exchangeRate1 = amazonShopExchangeRates.get(0).getExchangeRate1();
                                                                exchangeRate2 = amazonShopExchangeRates.get(0).getExchangeRate2();
                                                            }

                                                        }
                                                        amazonShopOrder = new AmazonShopOrder();
                                                        amazonShopOrder.setShopGuid(amazonShop.getGuid());
                                                        amazonShopOrder.setAmazonOrderId(amazonOrderId);
                                                        amazonShopOrder.setMarketplaceId(amazonShop.getMarketplaceIds());
                                                        if (purchaseDate.contains("+")) {
                                                            purchaseDate = purchaseDate.substring(0, purchaseDate.indexOf("+"));
                                                        }
                                                        if (lastUpdateDate.contains("+")) {
                                                            lastUpdateDate = lastUpdateDate.substring(0, lastUpdateDate.indexOf("+"));
                                                        }
                                                        amazonShopOrder.setPurchaseDate(DateUtils.convertTDateToDate2(purchaseDate));
                                                        //一、欧洲店铺全部参照英国
                                                        //1、每年3月最后一个星期天~每年10月最后一个星期六，取BST（英国夏时令），本地时间=创建时间+1小时；
                                                        //2、每年10月最后一个星期天~次年3月最后一个星期六，取GMT（英国标准时令），本地时间=创建时间；
                                                        //二、美国店铺
                                                        //1、每年3月第二个星期天~每年11月第一个星期六，取PST（美国夏时令），本地时间=创建时间-8小时；
                                                        //2、每年11月第一个星期天~每年3月第二个星期六，取PDT（美国标准时令），本地时间=创建时间-7小时。
                                                        if (amazonShop.getRegionName().equals("欧洲")){
                                                            amazonShopOrder.setLocalDate(isDaylightSavings(amazonShopOrder.getPurchaseDate(),0));
                                                        } else if (amazonShop.getRegionName().equals("北美")){
                                                            amazonShopOrder.setLocalDate(isDaylightSavings(amazonShopOrder.getPurchaseDate(),1));
                                                        } else {
                                                            amazonShopOrder.setLocalDate(amazonShopOrder.getPurchaseDate());
                                                        }
                                                        amazonShopOrder.setLastUpdateDate(DateUtils.convertTDateToDate2(lastUpdateDate));
                                                        amazonShopOrder.setLatestDeliveryDate(null);
                                                        amazonShopOrder.setOrderStatus(orderStatus);
                                                        amazonShopOrder.setCurrencyCode(currency);
                                                        amazonShopOrder.setOrderMoney(TypeUtils.getSafeDouble(orderMoney, 0d));
                                                        amazonShopOrder.setAsin(asin);
                                                        amazonShopOrder.setSellerSku(sellerSku);
                                                        amazonShopOrder.setQuantityOrdered(TypeUtils.getSafeDouble(quantity, 0d));
                                                        amazonShopOrder.setItemTax(TypeUtils.getSafeDouble(itemTax, 0d));
                                                        double itemPrice = (TypeUtils.getSafeDouble(quantity, 0d) == 0) ? 0 : MathExtUtils.fmtPrice(TypeUtils.getSafeDouble(orderMoney, 0d) / TypeUtils.getSafeDouble(quantity, 0d), 2);
                                                        amazonShopOrder.setItemPrice(itemPrice);
                                                        amazonShopOrder.setSalesChannel(salesChannel);//销售渠道
                                                        amazonShopOrder.setExchangeRate1(exchangeRate1);
                                                        amazonShopOrder.setExchangeRate2(exchangeRate2);
                                                        amazonShopOrder.setOrderAmount(MathExtUtils.fmtPrice(amazonShopOrder.getOrderMoney() * exchangeRate2, 2));
                                                        amazonShopOrder.setPrice(MathExtUtils.fmtPrice(amazonShopOrder.getItemPrice() * exchangeRate2, 2));
                                                        amazonShopOrder.setTaxes(MathExtUtils.fmtPrice(amazonShopOrder.getItemTax() * exchangeRate2, 2));
                                                        amazonShopOrder.setCreateUser("0000");
                                                        amazonShopOrderList.add(amazonShopOrder);
                                                        amazonOrderNoList.add(amazonOrderId);
                                                    }
                                                }
                                            }catch (Exception ex){
                                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时出错！";
                                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时，具体错误为："+ex.getMessage());
                                            }
                                        }
                                    }catch (Exception ex){
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]并保存为cvs文件时出错！";
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]并保存为cvs文件时出错，具体错误为："+ex.getMessage());
                                    }
                                    finally {
                                        if (closeThis != null) {
                                            closeThis.close();
                                        }
                                    }
                                }
                            } else {
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReportDocument接口返回对象为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"具体错误为调用getReport接口返回对象为空！");
                            }
                        }else {
                            if(processingStatus != null && Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())){
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表["+nowDateStr+"]这天没有数据，其中report对象值："+ JSON.toJSONString(report);
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表["+nowDateStr+"]这天没有数据，其中report对象值为"+ JSON.toJSONString(report));
                            }else{
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReport接口返回reportDocumentId值为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"具体错误为调用getReport接口返回reportDocumentId值为空！");
                            }
                        }
                    }else {
                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中reportId值："+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！";
                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，其中reportId值为"+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！");
                    }
                }else{
                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，具体错误为调用createReport接口返回对象为空！";
                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，具体错误为调用createReport接口返回对象为空！");
                }
            }catch (com.bo.sellingpartnerapi.Reports20210630.invoker.ApiException ex){
                JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
                if (errorJson != null){
                    JSONArray errorList = errorJson.getJSONArray("errors");
                    if (errorList != null && errorList.size() > 0) {
                        errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
                        for (int i = 0; i < errorList.size(); i++) {
                            JSONObject failedItem = errorList.getJSONObject(i);
                            String message = failedItem.getString("message");
                            errorMsg += message + "\n\r";
                        }
                    }
                }
                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，具体错误为："+errorMsg;
                logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，错误信息为：" + ex.getResponseBody());
                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，错误信息为：" + errorMsg);
            }
        }catch(Exception ex){
            result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，具体错误为："+ex.getMessage();
            logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，错误信息为：" + ex.getMessage());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), result, 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息出错，错误信息为：" + ex.getMessage());
        }
        long end=System.currentTimeMillis();
        System.out.println("当前程序运行多少毫秒:" + "=" + (end-start));

        return  result;
    }

    /**
     * 获取单个店铺的订单信息通过接口(暂不了)
     * @param system
     * @param type
     * @param ordersApi
     * @param amazonShop
     * @param nextToken
     * @return
     */
    private String getAmazonShopOrderBySpApi(String system, String type, OrdersV0Api ordersApi, AmazonShop amazonShop, String nextToken, List<AmazonShopOrder> amazonShopOrderList, List<String> amazonOrderNoList, int batchNo){
        String result = "";
        String lastOrderSyncDate = amazonShop.getLastOrderSyncDate();
        if (StringUtils.isEmpty(lastOrderSyncDate)){
            lastOrderSyncDate = DateUtils.convertDateToTDate(new Date());
        }
        List<String> marketplaceIdList =  new ArrayList<>();
        if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
            String marketplaceIds = amazonShop.getMarketplaceIds();
            String[] marketplaceIdArray = marketplaceIds.split(",");
            marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
        }
        GetOrdersResponse response = null;
        String errorMsg = "";
        String errorItemMsg = "";
        List<String> empty = new ArrayList<>();
        int insertLogId = 0;
        AmazonShopOrder amazonShopOrder = null;
        boolean orderSuccess = false;
        int orderItemError = 0;
        try {
            insertLogId = apiLogService.addApiLog(system,type,"亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息，marketplaces："+JSON.toJSONString(marketplaceIdList) + "，createdAfter："+lastOrderSyncDate + "，nextToken："+nextToken + "，分页批次号["+ String.valueOf(batchNo)+"]","",0, "");
            response = ordersApi.getOrders(marketplaceIdList, lastOrderSyncDate, "", "", "", empty, empty, empty, "", "", 20, empty, nextToken, empty, "", null, "");
            if (response != null && (response.getErrors() == null || response.getErrors().size() == 0)){
                if (response.getPayload() != null && response.getPayload().getOrders() != null && response.getPayload().getOrders().size() > 0) {
                    for (Order order : response.getPayload().getOrders()) {
                        GetOrderItemsResponse itemsResponse = null;
                        try {
                            itemsResponse = ordersApi.getOrderItems(order.getAmazonOrderId(), "");
                            if (itemsResponse != null && (itemsResponse.getErrors() == null || itemsResponse.getErrors().size() == 0)) {
                                if (itemsResponse.getPayload() != null && itemsResponse.getPayload().getOrderItems() != null && itemsResponse.getPayload().getOrderItems().size() > 0) {
                                    for (OrderItem orderItem : itemsResponse.getPayload().getOrderItems()) {
                                        amazonShopOrder = new AmazonShopOrder();
                                        amazonShopOrder.setShopGuid(amazonShop.getGuid());
                                        amazonShopOrder.setAmazonOrderId(order.getAmazonOrderId());
                                        amazonShopOrder.setMarketplaceId(order.getMarketplaceId());
                                        amazonShopOrder.setPurchaseDate(DateUtils.convertTDateToDate(order.getPurchaseDate()));
                                        amazonShopOrder.setLastUpdateDate(DateUtils.convertTDateToDate(order.getLastUpdateDate()));
                                        amazonShopOrder.setLatestDeliveryDate(DateUtils.convertTDateToDate(order.getLatestShipDate()));
                                        amazonShopOrder.setOrderStatus(order.getOrderStatus().toString());
                                        if (order.getOrderTotal() != null) {
                                            amazonShopOrder.setCurrencyCode(order.getOrderTotal().getCurrencyCode());
                                            amazonShopOrder.setOrderMoney(TypeUtils.getSafeDouble(order.getOrderTotal().getAmount(), 0d));
                                        }
                                        amazonShopOrder.setAsin(orderItem.getASIN());
                                        amazonShopOrder.setSellerSku(orderItem.getSellerSKU());
                                        amazonShopOrder.setQuantityOrdered(orderItem.getQuantityOrdered());
                                        if (orderItem.getItemTax() != null) {
                                            amazonShopOrder.setItemTax(TypeUtils.getSafeDouble(orderItem.getItemTax().getAmount(), 0d));
                                        }
                                        if (orderItem.getItemPrice() != null) {
                                            amazonShopOrder.setItemPrice(TypeUtils.getSafeDouble(orderItem.getItemPrice().getAmount(), 0d));
                                        }
                                        amazonShopOrder.setCreateUser("0000");
                                        amazonShopOrderList.add(amazonShopOrder);
                                        amazonOrderNoList.add(order.getAmazonOrderId());
                                    }
                                }
                            } else {
                                com.bo.sellingpartnerapi.Ordersv0.model.ErrorList errorList = itemsResponse.getErrors();
                                if (errorList != null && errorList.size() > 0){
                                    errorItemMsg = errorItemMsg + "获取亚马逊订单号["+ order.getAmazonOrderId() +"]明细数据失败原因1如下：";
                                    for (com.bo.sellingpartnerapi.Ordersv0.model.Error errorItem: errorList) {
                                        errorItemMsg += errorItem.getMessage() + "\n\r";
                                    }
                                }
                            }
                        }catch (com.bo.sellingpartnerapi.Ordersv0.invoker.ApiException itemEx) {
                            JSONObject errorJson = JSONObject.parseObject(itemEx.getResponseBody());
                            if (errorJson != null){
                                JSONArray errorList = errorJson.getJSONArray("errors");
                                if (errorList != null && errorList.size() > 0) {
                                    errorItemMsg = errorItemMsg + "获取亚马逊订单号["+ order.getAmazonOrderId() +"]明细数据失败原因2如下：";
                                    for (int i = 0; i < errorList.size(); i++) {
                                        JSONObject failedItem = errorList.getJSONObject(i);
                                        String message = failedItem.getString("message");
                                        errorItemMsg += message + "\n\r";
                                    }
                                }
                            }
                        }
                    }
                    if (StringUtils.isEmpty(errorItemMsg)) {
                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]订单信息，marketplaces：" + JSON.toJSONString(marketplaceIdList) + "，createdAfter：" + lastOrderSyncDate + "，nextToken：" + nextToken+ "，分页批次号["+ String.valueOf(batchNo)+"]", JSON.toJSONString(response), 0, "ECP_API调用获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]订单信息成功！");
                    }else{
                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]订单信息，marketplaces：" + JSON.toJSONString(marketplaceIdList) + "，createdAfter：" + lastOrderSyncDate + "，nextToken：" + nextToken+ "，分页批次号["+ String.valueOf(batchNo)+"]", JSON.toJSONString(response), 0, "ECP_API调用获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]订单信息成功，其中订单明细获取失败有："+errorItemMsg);
                    }
                    if (!StringUtils.isEmpty(response.getPayload().getNextToken())){
                        batchNo++;
                        getAmazonShopOrderBySpApi(system, type, ordersApi, amazonShop, response.getPayload().getNextToken(), amazonShopOrderList, amazonOrderNoList,batchNo);
                    }
                }
            }else{
                com.bo.sellingpartnerapi.Ordersv0.model.ErrorList errorList = response.getErrors();
                if (errorList != null && errorList.size() > 0){
                    for (com.bo.sellingpartnerapi.Ordersv0.model.Error errorItem: errorList) {
                        errorMsg += errorMsg + errorItem.getMessage() + "\n\r";
                    }
                    result = "获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，具体错误为："+errorMsg;
                }
                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，具体错误为："+errorMsg;
                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息，marketplaces："+JSON.toJSONString(marketplaceIdList) + "，createdAfter："+lastOrderSyncDate+ "，nextToken："+nextToken+ "，分页批次号["+ String.valueOf(batchNo)+"]", JSON.toJSONString(response), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + errorMsg);
            }
        }catch (com.bo.sellingpartnerapi.Ordersv0.invoker.ApiException ex){
            JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
            if (errorJson != null){
                JSONArray errorList = errorJson.getJSONArray("errors");
                if (errorList != null && errorList.size() > 0) {
                    errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
                    for (int i = 0; i < errorList.size(); i++) {
                        JSONObject failedItem = errorList.getJSONObject(i);
                        String message = failedItem.getString("message");
                        errorMsg += message + "\n\r";
                    }
                }
            }
            result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，具体错误为："+errorMsg;
            logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + ex.getResponseBody());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息，marketplaces："+JSON.toJSONString(marketplaceIdList) + ",createdAfter："+lastOrderSyncDate+ "，nextToken："+nextToken+ "，分页批次号["+ String.valueOf(batchNo)+"]", result, 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + ex.getResponseBody());
        }catch (Exception ex2){
            result = "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + ex2.getMessage();
            logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + ex2.getMessage());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息，marketplaces："+JSON.toJSONString(marketplaceIdList) + ",createdAfter："+lastOrderSyncDate+ "，nextToken："+nextToken+ "，分页批次号["+ String.valueOf(batchNo)+"]", result, 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单信息出错，错误信息为：" + ex2.getMessage());
        }
        return  result;
    }

    @Override
    public ApiResponse getAllAmazonShopProductInfo(int insertLogId, String system, String type, Map<String, Object> queryParams) {
        ApiResponse apiResponse = new ApiResponse();
        StringBuilder messageBuilder = new StringBuilder();
        AmazonShopProduct amazonShopProduct = null;
        Date nowDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = simpleDateFormat.format(nowDate);
        String updateUserId = "0000";//默认为0000，手动调用时，以调用者作为用户记录
        if (queryParams.containsKey("userId")){
            updateUserId = (String) queryParams.get("userId");
        }
        try {
            List<AmazonShopProduct> amazonShopProductList = amazonShopProductMapper.findAmazonShopProductList(queryParams);
            if (amazonShopProductList != null && amazonShopProductList.size() > 0) {
                for (AmazonShopProduct productItem : amazonShopProductList) {
                    if(StringUtils.isEmpty(productItem.getRefreshToken()) || StringUtils.isEmpty(productItem.getRegionCode())){
                        continue;
                    }
                    //获取区域对应的端点枚举，取不到直接跳转过
                    RegionEnum regionEnum = RegionEnum.from(productItem.getRegionCode().toUpperCase());
                    if (regionEnum == null){
                        continue;
                    }
                    AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                            .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                            .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                            .region(regionEnum.getAwsRegion())
                            .build();
                    AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                            .roleArn(ApiConfig.getAmazonRoleArn())
                            .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                            .build();
                    LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                            .clientId(ApiConfig.getAmazonLwaClientKey())
                            .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                            .refreshToken(productItem.getRefreshToken())
                            .endpoint(ApiConfig.getAmazonLwaEndpoint())
                            .build();

                    String asin = productItem.getAsin();
                    String fnSku = productItem.getFnSku();
                    //如果asin为空，调用get Listings Item接口通过sku获取
                    if (StringUtils.isEmpty(asin)){
                        ListingsApi listingsApi = new ListingsApi.Builder()
                                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                                .endpoint(regionEnum.getServiceUrl())
                                .build();
                        List<String> listMarketplaceIds = new ArrayList<String>();
                        listMarketplaceIds.add(productItem.getMarketplaceId());
                        List<String> listIncludedData = new ArrayList<>();
                        listIncludedData.add("issues");
                        listIncludedData.add("attributes");
                        listIncludedData.add("summaries");
                        listIncludedData.add("offers");
                        listIncludedData.add("fulfillmentAvailability");
                        String listIssueLocale = "en_US";
                        Item listingsItem = null;
                        try{
                            listingsItem = listingsApi.getListingsItem(productItem.getSellerId(), productItem.getSellerSku(),listMarketplaceIds, listIssueLocale, listIncludedData);
                        }catch (com.bo.sellingpartnerapi.Listingsitems20210801.invoker.ApiException ex){
                            logger.error("获取SKU["+ productItem.getSellerSku() +"]ListingsApi接口信息出错，具体错误为："+ex.getResponseBody());
                        }catch (Exception e){
                            logger.error("获取SKU["+ productItem.getSellerSku() +"]ListingsApi接口信息出错，具体错误为："+e.getMessage());
                        }
                        if (listingsItem != null &&  listingsItem.getSummaries() != null &&  listingsItem.getSummaries().size() > 0){
                            for (ItemSummaryByMarketplace itemSummaryByMarketplace: listingsItem.getSummaries()) {
                                asin = itemSummaryByMarketplace.getAsin();
                                fnSku = itemSummaryByMarketplace.getFnSku();
                            }
                        }
                    }
                    //如果上面获取asin获取不到，这边直接跳到下个循环
                    if (StringUtils.isEmpty(asin)){
                        continue;
                    }
                    amazonShopProduct = new AmazonShopProduct();
                    amazonShopProduct.setGuid(productItem.getGuid());
                    amazonShopProduct.setAsin(asin);
                    amazonShopProduct.setFnSku(fnSku);
                    //当asin不为空时，才调用以下接口
                    if (!StringUtils.isEmpty(asin)){
                        //根据get Catalog Item获取产品相关信息
                        CatalogApi catalogApi = new CatalogApi.Builder()
                                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                                .endpoint(regionEnum.getServiceUrl())
                                .build();
                        List<String> catalogMarketplaceIds = new ArrayList<String>();
                        catalogMarketplaceIds.add(productItem.getMarketplaceId());
                        List<String> catalogIncludedData = new ArrayList<>();
                        catalogIncludedData.add("attributes");
                        catalogIncludedData.add("dimensions");
                        catalogIncludedData.add("identifiers");
                        catalogIncludedData.add("images");
                        catalogIncludedData.add("productTypes");
                        catalogIncludedData.add("salesRanks");
                        catalogIncludedData.add("summaries");
                        catalogIncludedData.add("relationships");
                        com.bo.sellingpartnerapi.Catalogitems20220401.model.Item catalogItem = null;
                        try {
                            catalogItem = catalogApi.getCatalogItem(asin, catalogMarketplaceIds, catalogIncludedData, "en_US");
                        }catch (com.bo.sellingpartnerapi.Catalogitems20220401.invoker.ApiException ex){
                            logger.error("获取SKU["+ productItem.getSellerSku() +"]CatalogApi下Catalogitems20220401接口信息出错，具体错误为："+ex.getResponseBody());
                        }
                        if (catalogItem != null){
                            //获取产品品牌
                            if (catalogItem.getSummaries() != null && catalogItem.getSummaries().size() > 0){
                                com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSummaryByMarketplace itemSummaryByMarketplace = catalogItem.getSummaries().get(0);
                                if (itemSummaryByMarketplace != null){
                                    amazonShopProduct.setBrand(itemSummaryByMarketplace.getBrand());
                                }
                            }
                            //获取产品图片
                            if (catalogItem.getImages() != null && catalogItem.getImages().size() >0){
                                com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImagesByMarketplace itemImagesByMarketplace= catalogItem.getImages().get(0);
                                if (itemImagesByMarketplace != null && itemImagesByMarketplace.getImages() != null && itemImagesByMarketplace.getImages().size() > 0){
                                    com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemImage itemImage = itemImagesByMarketplace.getImages().get(0);
                                    if (itemImage != null){
                                        amazonShopProduct.setMainImage(itemImage.getLink());
                                    }
                                }
                            }
                            //获取产品类别
                            if (catalogItem.getProductTypes() != null && catalogItem.getProductTypes().size() > 0){
                                com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemProductTypeByMarketplace itemProductTypeByMarketplace = catalogItem.getProductTypes().get(0);
                                if(itemProductTypeByMarketplace != null){
                                    amazonShopProduct.setProductType(itemProductTypeByMarketplace.getProductType());
                                }
                            }
                            //获取产品排名
                            if (catalogItem.getSalesRanks() != null && catalogItem.getSalesRanks().size() > 0){
                                com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemSalesRanksByMarketplace itemSalesRanksByMarketplace = catalogItem.getSalesRanks().get(0);
                                if (itemSalesRanksByMarketplace != null && itemSalesRanksByMarketplace.getDisplayGroupRanks() != null && itemSalesRanksByMarketplace.getDisplayGroupRanks().size() > 0){
                                    com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDisplayGroupSalesRank itemDisplayGroupSalesRank = itemSalesRanksByMarketplace.getDisplayGroupRanks().get(0);
                                    if (itemDisplayGroupSalesRank != null){
                                        amazonShopProduct.setSalesRank(itemDisplayGroupSalesRank.getRank());
                                    }
                                }
                            }
                            //获取产品尺寸与包装尺寸
                            if (catalogItem.getDimensions() != null && catalogItem.getDimensions().size() >0){
                                com.bo.sellingpartnerapi.Catalogitems20220401.model.ItemDimensionsByMarketplace itemDimensionsByMarketplace = catalogItem.getDimensions().get(0);
                                if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getItem() != null){
                                    amazonShopProduct.setSizeLength((itemDimensionsByMarketplace.getItem().getLength() != null && itemDimensionsByMarketplace.getItem().getLength().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getLength().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);//将英寸转成厘米
                                    amazonShopProduct.setSizeHeight((itemDimensionsByMarketplace.getItem().getHeight() != null && itemDimensionsByMarketplace.getItem().getHeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getHeight().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);
                                    amazonShopProduct.setSizeWidth((itemDimensionsByMarketplace.getItem().getWidth() != null && itemDimensionsByMarketplace.getItem().getWidth().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getItem().getWidth().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);
                                }
                                if (itemDimensionsByMarketplace != null && itemDimensionsByMarketplace.getPackage() != null){
                                    amazonShopProduct.setPackageLength((itemDimensionsByMarketplace.getPackage().getLength() != null && itemDimensionsByMarketplace.getPackage().getLength().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getLength().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);
                                    amazonShopProduct.setPackageHeight((itemDimensionsByMarketplace.getPackage().getHeight() != null && itemDimensionsByMarketplace.getPackage().getHeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getHeight().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);
                                    amazonShopProduct.setPackageWidth((itemDimensionsByMarketplace.getPackage().getWidth() != null && itemDimensionsByMarketplace.getPackage().getWidth().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getWidth().getValue().multiply(new BigDecimal("2.54")).doubleValue(),2) :0d);
                                    amazonShopProduct.setPackageWeight((itemDimensionsByMarketplace.getPackage().getWeight()!= null && itemDimensionsByMarketplace.getPackage().getWeight().getValue() != null) ? MathExtUtils.fmtPrice(itemDimensionsByMarketplace.getPackage().getWeight().getValue().multiply(new BigDecimal("0.45359237")).doubleValue(),2):0d);//将磅转成千克
                                }
                            }
                        }
                        //根据get Inventory Summaries获取库存信息
                        FbaInventoryApi fbaInventoryApi = new FbaInventoryApi.Builder()
                                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                                .endpoint(regionEnum.getServiceUrl())
                                .build();
                        String granularityType = "Marketplace";
                        String granularityId = productItem.getMarketplaceId();
                        List<String> fbaInventoryMarketplaceIds = new ArrayList<String>();
                        fbaInventoryMarketplaceIds.add(productItem.getMarketplaceId());
                        List<String> fbaInventorySellerSkus = new ArrayList<>();
                        fbaInventorySellerSkus.add(productItem.getSellerSku());
                        GetInventorySummariesResponse inventorySummariesResponse = null;
                        try {
                            inventorySummariesResponse = fbaInventoryApi.getInventorySummaries(granularityType, granularityId, fbaInventoryMarketplaceIds, true, null, fbaInventorySellerSkus, "");
                        }
                        catch (com.bo.sellingpartnerapi.Fbainventory.invoker.ApiException ex){
                            logger.error("获取SKU["+ productItem.getSellerSku() +"]FbaInventoryApi接口信息出错，具体错误为："+ex.getResponseBody());
                        }catch (Exception ex2){
                            logger.error("获取SKU["+ productItem.getSellerSku() +"]FbaInventoryApi接口信息出错，具体错误为："+ex2.getMessage());
                        }
                        if (inventorySummariesResponse != null){
                            if (inventorySummariesResponse.getPayload() != null && inventorySummariesResponse.getPayload().getInventorySummaries() != null && inventorySummariesResponse.getPayload().getInventorySummaries().size() > 0){
                                com.bo.sellingpartnerapi.Fbainventory.model.InventorySummary inventorySummary = inventorySummariesResponse.getPayload().getInventorySummaries().get(0);
                                if (inventorySummary != null){
                                    amazonShopProduct.setLastUpdatedTime(DateUtils.convertTDateToDate(inventorySummary.getLastUpdatedTime().toString()));
                                    if (inventorySummary.getInventoryDetails() != null) {
                                        com.bo.sellingpartnerapi.Fbainventory.model.InventoryDetails inventoryDetails = inventorySummary.getInventoryDetails();
                                        if (inventoryDetails != null) {
                                            amazonShopProduct.setFulfillableQuantity(inventoryDetails.getFulfillableQuantity());
                                            amazonShopProduct.setInboundWorkingQuantity(inventoryDetails.getInboundShippedQuantity());
                                            if (inventoryDetails.getUnfulfillableQuantity() != null){
                                                amazonShopProduct.setUnfulfillableQuantity(inventoryDetails.getUnfulfillableQuantity().getTotalUnfulfillableQuantity());
                                            }
                                            if (inventoryDetails.getResearchingQuantity() != null){
                                                amazonShopProduct.setReservedQuantity(inventoryDetails.getReservedQuantity().getTotalReservedQuantity());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        SellerSecretsVO secretsVO = new SellerSecretsVO();
                        secretsVO.setAWSAuthenticationCredentials_AK(ApiConfig.getAmazonAwsAccessKey());
                        secretsVO.setAWSAuthenticationCredentials_SK(ApiConfig.getAmazonAwsAccessSecret());
                        secretsVO.setAWSAuthenticationCredentialsProvider_roleArn(ApiConfig.getAmazonRoleArn());
                        secretsVO.setlWAAuthorizationCredentials_clientid(ApiConfig.getAmazonLwaClientKey());
                        secretsVO.setLWAAuthorizationCredentials_clientSecret(ApiConfig.getAmazonLwaClientSecret());
                        secretsVO.setSeller_id(productItem.getSellerId());
                        secretsVO.setLWAAuthorizationCredentials_refreshToken(productItem.getRefreshToken());
                        if ("欧洲".equals(productItem.getRegionName())) {
                            secretsVO.setMarketPlace(MarketplaceEnum.EUROPE.getCode());
                        } else if ("北美".equals(productItem.getRegionName())) {
                            secretsVO.setMarketPlace(MarketplaceEnum.NORTH.getCode());
                        } else if ("远东".equals(productItem.getRegionName())) {
                            secretsVO.setMarketPlace(MarketplaceEnum.ASIA.getCode());
                        }

                        String code = "";
                        //根据站点对应的货件站点
                        AmazonSellerUrlEnum[] AmazonSellerUrlEnumList = AmazonSellerUrlEnum.values();
                        for (AmazonSellerUrlEnum amazonSellerUrlEnum : AmazonSellerUrlEnumList){
                            if(productItem.getCountryName().equals(amazonSellerUrlEnum.getCnName())){
                                code = amazonSellerUrlEnum.getCode();
                            }
                        }

                        FbaInboundApi fbaInboundApi = Helper.buildApi(secretsVO, FbaInboundApi.class);
                        GetPrepInstructionsResponse getPrepInstructionsResponseList = fbaInboundApi.getPrepInstructions(code, fbaInventorySellerSkus, null);
                        StringBuilder prepInstructionList = new StringBuilder();
                        if (getPrepInstructionsResponseList != null){
                            GetPrepInstructionsResult payload = getPrepInstructionsResponseList.getPayload();
                            if (payload.getSkUPrepInstructionsList() != null){
                                for(SKUPrepInstructions skuPrepInstructions :payload.getSkUPrepInstructionsList()){
                                    if (skuPrepInstructions.getPrepInstructionList() != null){
                                        for (PrepInstruction prepInstruction : skuPrepInstructions.getPrepInstructionList()){
                                            if(prepInstructionList.length()!=0){
                                                prepInstructionList.append(","+prepInstruction.getValue());
                                            }else{
                                                prepInstructionList.append(prepInstruction.getValue());
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //保存产品更新信息
                        amazonShopProduct.setPrepInstructionList(prepInstructionList.toString());
                        amazonShopProduct.setUpdateTime(new Date());
                        amazonShopProduct.setUpdateUser(updateUserId);
                        amazonShopProductMapper.update(amazonShopProduct);
//                        //保存当天查询到的产品报表排名信息
//                        Map<String, Object> reportMap = new HashMap<>();
//                        reportMap.put("shopProductGuid", productItem.getGuid());
//                        reportMap.put("dataDate", nowDateStr);
//                        AmazonShopProductReport amazonShopProductReport = amazonShopProductMapper.findAmazonShopProductReportByMap(reportMap);
//                        if (amazonShopProductReport !=  null){
//                            amazonShopProductReport.setSalesRank(amazonShopProduct.getSalesRank());
//                            amazonShopProductReport.setShopProductGuid(productItem.getGuid());
//                            amazonShopProductReport.setUpdateTime(new Date());
//                            amazonShopProductMapper.updateAmazonShopProductReport(amazonShopProductReport);
//                        }else{
//                            amazonShopProductReport = new AmazonShopProductReport();
//                            amazonShopProductReport.setShopProductGuid(productItem.getGuid());
//                            amazonShopProductReport.setSalesRank(amazonShopProduct.getSalesRank());
//                            amazonShopProductReport.setDataDate(nowDateStr);
//                            amazonShopProductMapper.insertAmazonShopProductReport(amazonShopProductReport);
//                        }
                    }
                }
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiLogService.updateApiLog(insertLogId, system, type, "queryParams："+JSON.toJSONString(queryParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取亚马逊店铺产品相关信息接口出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API调用获取亚马逊店铺产品相关信息接口出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }

    @Override
    public ApiResponse getAllAmazonShopProductPriceReport(int insertLogId, String system, String type, Map<String, Object> queryParams) {
        ApiResponse apiResponse = new ApiResponse();
        StringBuilder messageBuilder = new StringBuilder();
        try {
            List<AmazonShop> amazonShopList = amazonShopMapper.findAmazonShopList(queryParams);
            if (amazonShopList != null && amazonShopList.size() >0) {
                for (AmazonShop item : amazonShopList) {
                    if(StringUtils.isEmpty(item.getRefreshToken()) || StringUtils.isEmpty(item.getRegionCode())){
                        continue;
                    }
                    String methodResult = getAmazonShopProductPriceReport(system, type, item);
                    if (!StringUtils.isEmpty(methodResult)){
                        messageBuilder.append(methodResult);
                    }
                }
            }
            if (!StringUtils.isEmpty(messageBuilder.toString())){
                apiResponse.setMessage("获取店铺亚马逊店铺商品LISTINGS报表成功！，其中失败的如下：\n\r" + messageBuilder.toString());
            }else{
                apiResponse.setMessage("获取店铺亚马逊店铺商品LISTINGS报表成功！");
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiLogService.updateApiLog(insertLogId, system, type, "queryParams："+JSON.toJSONString(queryParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取亚马逊店铺商品LISTINGS报表接口出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API调用获取亚马逊店铺商品LISTINGS报表接口出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }


    /**
     * 单个店铺获取商品LISTINGS报表方法
     * @param system
     * @param type
     * @param amazonShop
     * @return
     */
    private String getAmazonShopProductPriceReport(String system, String type, AmazonShop amazonShop){
        int insertLogId = 0;
        Date nowDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = simpleDateFormat.format(nowDate);
        Date startTime = new Date();
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        String startTimeStr = DateUtils.convertDateToTDate(startTime);
        Date endTime = new Date();
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        String endTimeStr = DateUtils.convertDateToTDate(endTime);
        String errorMsg = "";
        String result = "";
        List<String> marketplaceIdList =  new ArrayList<>();
        if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
            String marketplaceIds = amazonShop.getMarketplaceIds();
            String[] marketplaceIdArray = marketplaceIds.split(",");
            marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
        }
        CreateReportSpecification body = new CreateReportSpecification();
        body.setReportType("GET_MERCHANT_LISTINGS_ALL_DATA");
        body.setMarketplaceIds(marketplaceIdList);
        body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
        body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
        ReportOptions reportOptions = new ReportOptions();
        reportOptions.put("custom", "true");
        body.setReportOptions(reportOptions);
        try {
            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());
            if (regionEnum == null){
                result = "店铺绑定的区域对应端点枚举获取不到，请检查！";
                return  result;
            }

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi reportsApi = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();

            CreateReportResponse reportResponse =  null;
            insertLogId = apiLogService.addApiLog(system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), "", 0, "");
            try {
                reportResponse = reportsApi.createReport(body);
                if (reportResponse != null){
                    String reportId = reportResponse.getReportId();
                    String reportDocumentId = "";
                    Report report = null;
                    Report.ProcessingStatusEnum processingStatus = null;
                    while (true){
                        report = reportsApi.getReport(reportId);
                        processingStatus = report.getProcessingStatus();
                        if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
                            if (report != null) {
                                reportDocumentId = report.getReportDocumentId();
                            }
                            break;
                        }else {
                            Thread.sleep(10000L);
                            continue;
                        }
                    }
                    if (report != null){
                        if (!StringUtils.isEmpty(reportDocumentId)) {
                            ReportDocument reportDocument = reportsApi.getReportDocument(reportDocumentId);
                            if (reportDocument != null) {
                                String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
                                OkHttpClient httpclient = new OkHttpClient();
                                httpclient.setConnectTimeout(30, TimeUnit.SECONDS);
                                httpclient.setReadTimeout(30, TimeUnit.SECONDS);
                                httpclient.setWriteTimeout(30, TimeUnit.SECONDS);
                                Request request = new Request.Builder()
                                        .url(reportDocument.getUrl())
                                        .get()
                                        .build();

                                Response httpResponse = httpclient.newCall(request).execute();
                                if (!httpResponse.isSuccessful()) {
                                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
                                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message());
                                    return result;
                                }
                                try (ResponseBody responseBody = httpResponse.body()) {
                                    MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                                    Charset charset = mediaType.charset();
                                    if (charset == null) {
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString();
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString());
                                        return result;
                                    }
                                    Closeable closeThis = null;
                                    try {
                                        InputStream inputStream = responseBody.byteStream();
                                        closeThis = inputStream;
                                        if ("GZIP".equals(compressionAlgorithm)) {
                                            inputStream = new GZIPInputStream(inputStream);
                                            closeThis = inputStream;
                                        }
                                        if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                                            closeThis = inputStreamReader;
                                            BufferedReader reader = new BufferedReader(inputStreamReader);
                                            closeThis = reader;
                                            StringBuilder stringBuilder = new StringBuilder();
                                            String line ;
                                            do {
                                                line = reader.readLine();
                                                if (line != null) {
                                                    stringBuilder.append(line);
                                                    stringBuilder.append("\n");
                                                }
                                            } while (line != null);
                                            String filePath = Global.getProfile() + "/amazonreport/listings/"+nowDateStr.replace("-", "");
                                            String fileName = "listings_report_" + amazonShop.getGuid()+ ".cvs";
                                            File file = new File(filePath);
                                            if(!file.exists()){
                                                file.mkdirs();
                                            }
                                            File reportFile = new File(filePath + "/"+ fileName);
                                            if (!reportFile.exists()){
                                                reportFile.createNewFile();
                                            }
                                            OutputStream outputStream = new FileOutputStream(reportFile);
                                            outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                                            outputStream.close();
                                            BufferedReader csvBufferedReader = null;
                                            String reportLine = "";
                                            String separator = "\t";
                                            try {
                                                InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/" + fileName), StandardCharsets.UTF_8);
                                                csvBufferedReader = new BufferedReader(csvInputStreamReader);
                                                String title = csvBufferedReader.readLine();
                                                String[] titleSplit = title.split(separator);
                                                while ((reportLine = csvBufferedReader.readLine()) != null) {
                                                    if (!StringUtils.isEmpty(reportLine)) {
                                                        //内容数组
                                                        String[] reportArray = reportLine.split(separator);
                                                        //判断内容和标题的size
                                                        if ((reportArray.length) < titleSplit.length) {
                                                            int len = titleSplit.length - reportArray.length;
                                                            reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
                                                        }
                                                        String sellerSku = reportArray[3];
                                                        String priceStr = reportArray[4];
                                                        String asin = reportArray[16];
                                                        //更新店铺商品表价格字段
                                                        Map<String, Object> queryProductMap = new HashMap<>();
                                                        queryProductMap.put("sellerSku", sellerSku);
                                                        queryProductMap.put("asin", asin);
                                                        AmazonShopProduct queryProduct = amazonShopProductMapper.findAmazonShopProductBySkuAndAsin(queryProductMap);
                                                        if (queryProduct != null){//只保存存在店铺商品表中的SKU商品价格数据
                                                            Map<String, Object> productMap = new HashMap<>();
                                                            productMap.put("sellerSku", sellerSku);
                                                            productMap.put("asin", asin);
                                                            productMap.put("listingPrice", TypeUtils.getSafeDouble(priceStr, 0d));
                                                            productMap.put("updateTime", new Date());
                                                            amazonShopProductMapper.updateAmazonShopProduct(productMap);
                                                            //保存当天查询到的产品报表排名信息
                                                            Map<String, Object> reportMap = new HashMap<>();
                                                            reportMap.put("shopProductGuid", queryProduct.getGuid());
                                                            reportMap.put("dataDate", nowDateStr);
                                                            AmazonShopProductReport amazonShopProductReport = amazonShopProductMapper.findAmazonShopProductReportByMap(reportMap);
                                                            if (amazonShopProductReport !=  null){
                                                                amazonShopProductReport.setShopProductGuid(queryProduct.getGuid());
                                                                amazonShopProductReport.setListingPrice(TypeUtils.getSafeDouble(priceStr, 0d));
                                                                amazonShopProductReport.setUpdateTime(new Date());
                                                                amazonShopProductMapper.updateAmazonShopProductReport(amazonShopProductReport);
                                                            }else{
                                                                amazonShopProductReport = new AmazonShopProductReport();
                                                                amazonShopProductReport.setShopProductGuid(queryProduct.getGuid());
                                                                amazonShopProductReport.setListingPrice(TypeUtils.getSafeDouble(priceStr, 0d));
                                                                amazonShopProductReport.setDataDate(nowDateStr);
                                                                amazonShopProductMapper.insertAmazonShopProductReport(amazonShopProductReport);
                                                            }
                                                        }
                                                    }
                                                }
                                            }catch (Exception ex){
                                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时出错！";
                                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，处理读取CSV文件进行数据保存时，具体错误为："+ex.getMessage());
                                            }
                                        }
                                    }catch (Exception ex){
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地方为获取responseBody.byteStream()文件流出错！";
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地点为获取responseBody.byteStream()文件流出错，具体信息信息："+ex.getMessage());
                                    }
                                    finally {
                                        if(responseBody != null){
                                            responseBody.close();
                                        }
                                        if (closeThis != null) {
                                            closeThis.close();
                                        }
                                    }
                                }
                            } else {
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReportDocument接口返回对象为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"具体错误为调用getReport接口返回对象为空！");
                            }
                        }else {
                            if(processingStatus != null && Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())){
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表["+nowDateStr+"]这天没有数据，其中report对象值："+ JSON.toJSONString(report);
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表["+nowDateStr+"]这天没有数据，其中report对象值为"+ JSON.toJSONString(report));
                            }else {
                                result = "获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值：" + JSON.toJSONString(report) + "，具体错误为调用getReport接口返回reportDocumentId值为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中report对象值为" + JSON.toJSONString(report) + "具体错误为调用getReport接口返回reportDocumentId值为空！");
                            }
                        }
                    }else {
                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中reportId值："+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！";
                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，其中reportId值为"+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！");
                    }
                }else{
                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，具体错误为调用createReport接口返回对象为空！";
                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，具体错误为调用createReport接口返回对象为空！");
                }
            }catch (com.bo.sellingpartnerapi.Reports20210630.invoker.ApiException ex){
                JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
                if (errorJson != null){
                    JSONArray errorList = errorJson.getJSONArray("errors");
                    if (errorList != null && errorList.size() > 0) {
                        errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
                        for (int i = 0; i < errorList.size(); i++) {
                            JSONObject failedItem = errorList.getJSONObject(i);
                            String message = failedItem.getString("message");
                            errorMsg += message + "\n\r";
                        }
                    }
                }
                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，具体错误为："+errorMsg;
                logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，错误信息为：" + ex.getResponseBody());
                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，错误信息为：" + errorMsg);
            }
        }catch(Exception ex){
            result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，具体错误为："+ex.getMessage();
            logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，错误信息为：" + ex.getMessage());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), result, 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息出错，错误信息为：" + ex.getMessage());
        }
        return  result;
    }


    /**
     * 获取店铺单个区域的FBA库存信息
     * @param system
     * @param type
     * @param fbaInventoryApi
     * @param amazonShop
     * @param marketplaceId
     * @param nextToken
     * @return
     */
    private String getAmazonFbzInventory(String system, String type, FbaInventoryApi fbaInventoryApi, AmazonShop amazonShop,  String marketplaceId, String nextToken){
        String result = "";
        GetInventorySummariesResponse response = null;
        String granularityType = "Marketplace";
        String granularityId = marketplaceId;
        OffsetDateTime startDateTime = null;
        boolean details = true;
        List<String> sellerSkus = new ArrayList<>();
        List<String> marketplaceIds = new ArrayList<String>();
        marketplaceIds.add(marketplaceId);
        String errorMsg = "";
        int insertLogId = 0;
        try {
            insertLogId = apiLogService.addApiLog(system,type,"亚马逊店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]FBA库存信息，marketplaceIds："+JSON.toJSONString(marketplaceIds) ,"",0, "");
            response = fbaInventoryApi.getInventorySummaries(granularityType, granularityId, marketplaceIds, details, startDateTime, sellerSkus, nextToken);;
            if (response.getPayload() != null && response.getPayload().getInventorySummaries() != null && response.getPayload().getInventorySummaries().size() >0){
                for (InventorySummary inventorySummary : response.getPayload().getInventorySummaries()) {

                }
                Pagination pagination =  response.getPagination();
                if (pagination != null) {
                    if (!StringUtils.isEmpty(pagination.getNextToken())){
                        getAmazonFbzInventory(system, type, fbaInventoryApi, amazonShop, marketplaceId, pagination.getNextToken());
                    }
                }
            }else{
                com.bo.sellingpartnerapi.Fbainventory.model.ErrorList errorList = response.getErrors();
                if (errorList != null && errorList.size() > 0){
                    for (com.bo.sellingpartnerapi.Fbainventory.model.Error errorItem: errorList) {
                        errorMsg += errorMsg + errorItem.getMessage() + "\n\r";
                    }
                    result = "获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]区域为["+marketplaceId+"]的FBA库存信息出错，具体错误为："+errorMsg;
                }
                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]库存信息，marketplaces："+JSON.toJSONString(marketplaceIds) , result, 400, "ECP_API调用获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]区域为["+marketplaceId+"]的FBA库存信息出错，错误信息为：" + errorMsg);
            }
        }catch (com.bo.sellingpartnerapi.Fbainventory.invoker.ApiException ex){
            JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
            if (errorJson != null){
                JSONArray errorList = errorJson.getJSONArray("errors");
                if (errorList != null && errorList.size() > 0) {
                    errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
                    for (int i = 0; i < errorList.size(); i++) {
                        JSONObject failedItem = errorList.getJSONObject(i);
                        String message = failedItem.getString("message");
                        errorMsg += message + "\n\r";
                    }
                }
            }
            result = "获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]区域为["+marketplaceId+"]的FBA库存信息出错，具体错误为："+errorMsg;
            logger.error("ECP_API调用获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]FBA库存信息出错，错误信息为：" + ex.getResponseBody());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]FBA库存信息，marketplaces："+JSON.toJSONString(marketplaceIds) , result, 400, "ECP_API调用获取店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]区域为["+marketplaceId+"]的FBA库存信息出错，错误信息为：" + ex.getResponseBody());
        }
        return  result;
    }

    @Override
    public ApiResponse getAmazonSalesTrafficReport(int insertLogId, String system, String type, Map<String, Object> queryParams) {
        ApiResponse apiResponse = new ApiResponse();
        StringBuilder messageBuilder = new StringBuilder();
        try {
            List<AmazonShop> amazonShopList = amazonShopMapper.findGroupAmazonShopList(queryParams);
            if (amazonShopList != null && amazonShopList.size() >0) {
                for (AmazonShop item : amazonShopList) {
                    if(StringUtils.isEmpty(item.getRefreshToken()) || StringUtils.isEmpty(item.getRegionCode())){
                        continue;
                    }
                    //测试时指定一个店铺用
                    //if (!item.getShopUser().equals("SILULCM-GB")){
                        //continue;
                   // }
                    String methodResult = getAmazonShopProductSalesTrafficReport(system, type, item);
                    if (!StringUtils.isEmpty(methodResult)){
                        messageBuilder.append(methodResult);
                    }
                }
            }
            if (!StringUtils.isEmpty(messageBuilder.toString())){
                apiResponse.setMessage("获取店铺亚马逊店铺商品销售流量SALES_AND_TRAFFIC报表成功！，其中失败的如下：\n\r" + messageBuilder.toString());
            }else{
                apiResponse.setMessage("获取店铺亚马逊店铺商品销售流量SALES_AND_TRAFFIC报表成功！");
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiLogService.updateApiLog(insertLogId, system, type, "queryParams："+JSON.toJSONString(queryParams), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取亚马逊店铺商品销售流量SALES_AND_TRAFFIC报表接口出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API调用获取亚马逊店铺商品销售流量SALES_AND_TRAFFIC报表接口出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }

    /**
     * 单个店铺获取商品销售流量SALES_AND_TRAFFIC报表方法
     * @param system
     * @param type
     * @param amazonShop
     * @return
     */
    private String getAmazonShopProductSalesTrafficReport(String system, String type, AmazonShop amazonShop){
        int insertLogId = 0;
        Date nowDate = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, -1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = simpleDateFormat.format(calendar.getTime());
        Date startTime = calendar.getTime();
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        String startTimeStr = DateUtils.convertDateToTDate(startTime);
        Date endTime = calendar.getTime();
        endTime.setHours(23);
        endTime.setMinutes(59);
        endTime.setSeconds(59);
        String endTimeStr = DateUtils.convertDateToTDate(endTime);
        String errorMsg = "";
        String result = "";
        List<String> marketplaceIdList =  new ArrayList<>();
        if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
            String marketplaceIds = amazonShop.getMarketplaceIds();
            String[] marketplaceIdArray = marketplaceIds.split(",");
            marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
        }
        CreateReportSpecification body = new CreateReportSpecification();
        body.setReportType("GET_SALES_AND_TRAFFIC_REPORT");
        body.setMarketplaceIds(marketplaceIdList);
        body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
        body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
        ReportOptions reportOptions = new ReportOptions();
        reportOptions.put("dateGranularity","DAY");
        reportOptions.put("asinGranularity", "CHILD");
        body.setReportOptions(reportOptions);
        try {
            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());
            if (regionEnum == null){
                result = "店铺绑定的区域对应端点枚举获取不到，请检查！";
                return  result;
            }

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi reportsApi = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();

            CreateReportResponse reportResponse =  null;
            insertLogId = apiLogService.addApiLog(system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), "", 0, "");
            try {
                reportResponse = reportsApi.createReport(body);
                if (reportResponse != null){
                    String reportId = reportResponse.getReportId();
                    String reportDocumentId = "";
                    Report report = null;
                    Report.ProcessingStatusEnum processingStatus = null;
                    while (true){
                        report = reportsApi.getReport(reportId);
                        processingStatus = report.getProcessingStatus();
                        if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
                                || Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
                            if (report != null) {
                                reportDocumentId = report.getReportDocumentId();
                            }
                            break;
                        }else {
                            Thread.sleep(10000L);
                            continue;
                        }
                    }
                    if (report != null){
                        if (!StringUtils.isEmpty(reportDocumentId)) {
                            ReportDocument reportDocument = reportsApi.getReportDocument(reportDocumentId);
                            if (reportDocument != null) {
                                String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "":reportDocument.getCompressionAlgorithm().toString());
                                OkHttpClient httpclient = new OkHttpClient();
                                httpclient.setConnectTimeout(30, TimeUnit.SECONDS);
                                httpclient.setReadTimeout(30, TimeUnit.SECONDS);
                                httpclient.setWriteTimeout(30, TimeUnit.SECONDS);
                                Request request = new Request.Builder()
                                        .url(reportDocument.getUrl())
                                        .get()
                                        .build();

                                Response httpResponse = httpclient.newCall(request).execute();
                                if (!httpResponse.isSuccessful()) {
                                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
                                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message());
                                    return result;
                                }
                                try (ResponseBody responseBody = httpResponse.body()) {
                                    MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                                    Charset charset = mediaType.charset();
                                    if (charset == null) {
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString();
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错码为mediaType.charset()值为值，mediatype值为："+mediaType.toString());
                                        return result;
                                    }
                                    Closeable closeThis = null;
                                    try {
                                        InputStream inputStream = responseBody.byteStream();
                                        closeThis = inputStream;
                                        if ("GZIP".equals(compressionAlgorithm)) {
                                            closeThis = inputStream;
                                            inputStream = new GZIPInputStream(inputStream);
                                            byte[] zipBytes = ZipUtil.unGzip(inputStream);
                                            String filePath = Global.getProfile() + "/amazonreport/salestraffic/"+nowDateStr.replace("-", "");
                                            String gzOutPath =  filePath + "/salestraffic_report_" + amazonShop.getGuid();
                                            File gzOutFileObj= new File(gzOutPath);
                                            if(!gzOutFileObj.exists()){
                                                gzOutFileObj.mkdirs();
                                            }
                                            String gzFileNamePrefix = "salestraffic_report_" + amazonShop.getGuid();
                                            String fileName = gzFileNamePrefix +".txt";
                                            //将文件解压到gzOutPath目录中
                                            File gzOutFile = new File(gzOutPath + "/"+fileName);
                                            FileOutputStream fileOutputStream = new FileOutputStream(gzOutFile);
                                            fileOutputStream.write(zipBytes);
                                            fileOutputStream.close();
                                            File[] txtFileList = gzOutFileObj.listFiles();
                                            InputStream txtInputStream = null;
                                            StringBuffer txtStringBuffer = null;
                                            BufferedReader txtBufferedReader = null;
                                            if (txtFileList != null && txtFileList.length  > 0){
                                                for (File txtFileItem : txtFileList) {
                                                    txtInputStream = new FileInputStream(txtFileItem);
                                                    String txtLine; // 用来保存每行读取的内容
                                                    txtStringBuffer = new StringBuffer();
                                                    txtBufferedReader = new BufferedReader(new InputStreamReader(txtInputStream));
                                                    txtLine = txtBufferedReader.readLine(); // 读取第一行
                                                    while (txtLine != null) { // 如果 line 为空说明读完了
                                                        txtStringBuffer.append(txtLine); // 将读到的内容添加到 buffer 中
                                                        txtStringBuffer.append("\n"); // 添加换行符
                                                        txtLine = txtBufferedReader.readLine(); // 读取下一行
                                                    }
                                                    if(txtBufferedReader != null) txtBufferedReader.close();
                                                    if(txtInputStream != null) txtInputStream.close();
                                                    String txtContent = txtStringBuffer.toString();
                                                    if (!StringUtils.isEmpty(txtContent)){
                                                        JSONObject jsonObject = JSON.parseObject(txtContent);
                                                        if (jsonObject != null){
                                                            JSONArray jsonArray = jsonObject.getJSONArray("salesAndTrafficByAsin");
                                                            if (jsonArray != null && jsonArray.size() > 0){
                                                                for(int i=0;i<jsonArray.size();i++) {
                                                                    JSONObject itemJsonObj = jsonArray.getJSONObject(i);
                                                                    String asin = itemJsonObj.getString("parentAsin");
                                                                    JSONObject trafficByAsinObj = itemJsonObj.getJSONObject("trafficByAsin");
                                                                    Integer sessions = trafficByAsinObj.getInteger("pageViews");
                                                                    Double buyBoxPercentage = trafficByAsinObj.getDouble("buyBoxPercentage");
                                                                    Double sessionPercentage = trafficByAsinObj.getDouble("unitSessionPercentage");
                                                                    //保存当天查询到的产品报表排名信息
                                                                    Map<String, Object> reportMap = new HashMap<>();
                                                                    reportMap.put("asin", asin);
                                                                    reportMap.put("dataDate", nowDateStr);
                                                                    AmazonShopProductReport amazonShopProductReport = amazonShopProductMapper.findAmazonShopProductReportByMap(reportMap);
                                                                    if (amazonShopProductReport !=  null){
                                                                        amazonShopProductReport.setSessionsNum(sessions);
                                                                        amazonShopProductReport.setCommoditySession(sessionPercentage);
                                                                        amazonShopProductReport.setRecommendPrice(buyBoxPercentage);
                                                                        amazonShopProductReport.setUpdateTime(new Date());
                                                                        amazonShopProductMapper.updateAmazonShopProductReport(amazonShopProductReport);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                                            closeThis = inputStreamReader;
                                        }
                                    }catch (Exception ex){
                                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地方为获取responseBody.byteStream()文件流出错！";
                                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，错误信息为下载报表文件地址["+reportDocument.getUrl()+"]出错，出错地点为获取responseBody.byteStream()文件流出错，具体信息信息："+ex.getMessage());
                                    }
                                    finally {
                                        if(responseBody != null){
                                            responseBody.close();
                                        }
                                        if (closeThis != null) {
                                            closeThis.close();
                                        }
                                    }
                                }
                            } else {
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值："+ JSON.toJSONString(report)+"，具体错误为调用getReportDocument接口返回对象为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为"+ JSON.toJSONString(report)+"具体错误为调用getReport接口返回对象为空！");
                            }
                        }else {
                            if(processingStatus != null && Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())){
                                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表["+nowDateStr+"]这天没有数据，其中report对象值："+ JSON.toJSONString(report);
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表["+nowDateStr+"]这天没有数据，其中report对象值为"+ JSON.toJSONString(report));
                            }else {
                                result = "获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值：" + JSON.toJSONString(report) + "，具体错误为调用getReport接口返回reportDocumentId值为空！";
                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺[" + amazonShop.getShopUser() + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中report对象值为" + JSON.toJSONString(report) + "具体错误为调用getReport接口返回reportDocumentId值为空！");
                            }
                        }
                    }else {
                        result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中reportId值："+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！";
                        apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，其中reportId值为"+reportResponse.getReportId()+"，具体错误为调用getReport接口返回对象为空！");
                    }
                }else{
                    result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为调用createReport接口返回对象为空！";
                    apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为调用createReport接口返回对象为空！");
                }
            }catch (com.bo.sellingpartnerapi.Reports20210630.invoker.ApiException ex){
                JSONObject errorJson = JSONObject.parseObject(ex.getResponseBody());
                if (errorJson != null){
                    JSONArray errorList = errorJson.getJSONArray("errors");
                    if (errorList != null && errorList.size() > 0) {
                        errorMsg = errorMsg+ "，具体失败信息如下：\n\r";
                        for (int i = 0; i < errorList.size(); i++) {
                            JSONObject failedItem = errorList.getJSONObject(i);
                            String message = failedItem.getString("message");
                            errorMsg += message + "\n\r";
                        }
                    }
                }
                result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+errorMsg;
                logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，错误信息为：" + ex.getResponseBody());
                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), JSON.toJSONString(reportResponse), 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，错误信息为：" + errorMsg);
            }
        }catch(Exception ex){
            result = "获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，具体错误为："+ex.getMessage();
            logger.error("ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，错误信息为：" + ex.getMessage());
            apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品LISTINGS报表信息，post条件：" + JSON.toJSONString(body), result, 400, "ECP_API调用获取亚马逊单个店铺["+ amazonShop.getShopUser()  + "-" + amazonShop.getShopName() + "]商品销售流量SALES_AND_TRAFFIC报表信息出错，错误信息为：" + ex.getMessage());
        }
        return  result;
    }

    @Override
    public ApiResponse getAmazonAuthUrl(Map<String, Object> queryParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (queryParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数queryParams不能为空！");
                return apiResponse;
            }
            String shopId = (String) queryParams.get("shopId");
            String userId = (String) queryParams.get("userId");
            if (StringUtils.isEmpty(shopId) || StringUtils.isEmpty(userId)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中shopId与userId不能为空！");
                return apiResponse;
            }
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(shopId);
            if (amazonShop == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("参数中shopId对应的店铺信息不存在！");
                return apiResponse;
            }
            MarketplaceEnum marketplaceEnum = MarketplaceEnum.getEnumByCode(amazonShop.getRegionCode());
            if (marketplaceEnum == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("获取店铺对应的区域枚举出错！");
                return apiResponse;
            }
            String spApiAuthUrl = marketplaceEnum.getSpApiAuthUrl();
            //远东地区单选国家特殊处理
            if (MarketplaceEnum.ASIA.getCode().equals(marketplaceEnum.getCode())){
                AmazonSellerUrlEnum amazonSellerUrlEnum = AmazonSellerUrlEnum.getEnum(amazonShop.getRegionCountryCode());
                if (amazonSellerUrlEnum != null){
                    spApiAuthUrl = amazonSellerUrlEnum.getSellerCenterUrl();
                }
            }
            //沙特和阿联酋也需要特殊的amazonSellerUrlEnum.getSellerCenterUrl() 去获取
            spApiAuthUrl = spApiAuthUrl + String.format(ApiConfig.getAmazonSpApiAuthUrl(), ApiConfig.getAmazonAppKey(), amazonShop.getGuid());
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiResponse.setExtendAttr(spApiAuthUrl);
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API生成亚马逊授权URL地址出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API生成亚马逊授权URL地址出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }

    @Override
    public ApiResponse getAmazonToken(int insertLogId, String system, String type, String code, String shopId) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (code == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数code不能为空！");
                return apiResponse;
            }
            //String postParams = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", code, ApiConfig.getAmazonLwaClientKey(), ApiConfig.getAmazonLwaClientSecret());
            Map<String, String> postMapParams = new HashMap<>();
            postMapParams.put("grant_type", "authorization_code");
            postMapParams.put("code", code);
            postMapParams.put("client_id", ApiConfig.getAmazonLwaClientKey());
            postMapParams.put("client_secret", ApiConfig.getAmazonLwaClientSecret());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(ApiConfig.getAmazonLwaEndpoint(), postMapParams);
            String error = "";
            if (jsonObject != null) {
                if (jsonObject.containsKey("error")){
                    error = jsonObject.getString("error");
                }
                if (StringUtils.isEmpty(error)){
                    String access_token = jsonObject.getString("access_token");
                    String token_type = jsonObject.getString("token_type");
                    String refresh_token = jsonObject.getString("refresh_token");
                    int expires_in = jsonObject.getInteger("expires_in");
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.SECOND, expires_in);
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("guid", shopId);
                    updateMap.put("authorizeState", "已授权");
                    updateMap.put("accessToken", access_token);
                    updateMap.put("refreshToken", refresh_token);
                    updateMap.put("expireDate", calendar.getTime());
                    amazonShopMapper.updateByAccessToken(updateMap);
                    apiResponse.setSuccess(true);
                    apiResponse.setCode(0);
                }else{
                    String  errorDescription = jsonObject.getString("error_description");
                    apiResponse.setCode(400);
                    apiResponse.setMessage("获取亚马逊TOKEN失败，具体原因为"+errorDescription);
                }
            }else{
                apiResponse.setCode(400);
                apiResponse.setMessage("获取亚马逊TOKEN失败！");
            }
            apiLogService.updateApiLog(insertLogId, system, type, "code："+code + "，shopId："+shopId, JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API获取亚马逊授权TOKEN出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API获取亚马逊授权TOKEN出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }

    @Override
    public ApiResponse getAmazonTokenGg(int insertLogId, String system, String type, String code, String shopId) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (code == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数code不能为空！");
                return apiResponse;
            }
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(shopId);
            if (amazonShop == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("参数中shopId对应的店铺信息不存在！");
                return apiResponse;
            }
            MarketplaceEnum marketplaceEnum = MarketplaceEnum.getEnumByCode(amazonShop.getRegionCode());
            if (marketplaceEnum == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("获取店铺对应的区域枚举出错！");
                return apiResponse;
            }
            Map<String, String> postMapParams = new HashMap<>();
            postMapParams.put("grant_type", "authorization_code");
            postMapParams.put("code", code);
            postMapParams.put("client_id", ApiConfig.getAmazonClientId());
            postMapParams.put("client_secret", ApiConfig.getAmazonClientSecret());
            postMapParams.put("redirect_uri", ApiConfig.getAmazonRedirectUri());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(marketplaceEnum.getAdsAuthUrl(), postMapParams);
            String error = "";
            if (jsonObject != null) {
                if (jsonObject.containsKey("error")){
                    error = jsonObject.getString("error");
                }
                if (StringUtils.isEmpty(error)){
                    String access_token = jsonObject.getString("access_token");
                    String refresh_token = jsonObject.getString("refresh_token");
                    System.out.println("access_token = " + access_token + " ;refresh_token=" + refresh_token + "; amazonShop ="+ amazonShop.getShopName());
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("guid", shopId);
                    updateMap.put("authorizeStateGg", "已授权");
                    updateMap.put("accessTokenGg", access_token);
                    updateMap.put("refreshTokenGg", refresh_token);
                    amazonShopMapper.updateByAccessGgToken(updateMap);
                    apiResponse.setSuccess(true);
                    apiResponse.setCode(0);
                }else{
                    String  errorDescription = jsonObject.getString("error_description");
                    apiResponse.setCode(400);
                    apiResponse.setMessage("获取亚马逊TOKEN失败，具体原因为"+errorDescription);
                }
            }else{
                apiResponse.setCode(400);
                apiResponse.setMessage("获取亚马逊TOKEN失败！");
            }
            apiLogService.updateApiLog(insertLogId, system, type, "code："+code + "，shopId："+shopId, JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API获取亚马逊授权TOKEN出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API获取亚马逊授权TOKEN出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }


    /**
     * 亚马逊店铺是否失效
     * @param insertLogId
     * @param system
     * @param type
     * @param queryParams
     * @param startTime
     * @return
     */
    @Override
    public ApiResponse getAmazonShop( String system, String type, Map<String, Object> queryParams, Date startTime, Integer genre) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            List<AmazonShop> amazonShopList = amazonShopMapper.findGroupAmazonShopList(queryParams);
            if (amazonShopList != null && amazonShopList.size() >0){
                for (AmazonShop item:amazonShopList) {
                    boolean variable = true;
                    while (variable) {
                        for (Entry<String, Integer> e : THREAD_MAP.entrySet()) {
                            if (e.getValue() == 1) {
                                continue;
                            } else if (e.getValue() == 0) {
                                THREAD_MAP.put(e.getKey(), 1);
                                // 开启线程
                                Thread t = new Thread(() -> {
                                    if (!StringUtils.isEmpty(item.getRefreshToken()) && !StringUtils.isEmpty(item.getRegionCode())) {
                                        //获取不到区域对应的端点枚举，直接跳转过
                                        RegionEnum regionEnum = RegionEnum.from(item.getRegionCode().toUpperCase());
                                        if (regionEnum != null) {
                                            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                                                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                                                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                                                    .region(regionEnum.getAwsRegion())
                                                    .build();
                                            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                                                    .roleArn(ApiConfig.getAmazonRoleArn())
                                                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                                                    .build();
                                            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                                                    .clientId(ApiConfig.getAmazonLwaClientKey())
                                                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                                                    .refreshToken(item.getRefreshToken())
                                                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                                                    .build();
                                            OrdersV0Api ordersV0Api = new OrdersV0Api.Builder()
                                                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                                                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                                                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                                                    .endpoint(regionEnum.getServiceUrl())
                                                    .build();
                                            String lastOrderSyncDate = item.getLastOrderSyncDate();
                                            if (StringUtils.isEmpty(lastOrderSyncDate)) {
                                                lastOrderSyncDate = DateUtils.convertDateToTDate(new Date());
                                            }
                                            List<String> marketplaceIdList = new ArrayList<>();
                                            if (!StringUtils.isEmpty(item.getMarketplaceIds())) {
                                                String marketplaceIds = item.getMarketplaceIds();
                                                String[] marketplaceIdArray = marketplaceIds.split(",");
                                                marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
                                            }
                                            List<String> empty = new ArrayList<>();
                                            System.out.println(item.getShopName() + "测试");
                                            int insertLogId = apiLogService.addApiLog(system, type, "亚马逊单个店铺[" + item.getShopUser() + "-" + item.getShopName() + "]订单order报表信息，post条件：" + JSON.toJSONString(queryParams), "", 0, "");
                                            try {
                                                ordersV0Api.getOrders(marketplaceIdList, lastOrderSyncDate, "", "", "", empty, empty, empty, "", "", 20, empty, "", empty, "", null, "");
                                            } catch (Exception ex) {
                                                if (ex.getMessage().equals("Error getting LWA Access Token") || ex.getMessage().equals("Forbidden")) {
                                                    logger.info(item.getShopName() + "ECP_API调用订单实时数据判断是否失效，错误信息为：" + ex.getMessage());
                                                    //修改店铺失效状态
                                                    Map<String, Object> updateShopMap = new HashMap<>();
                                                    updateShopMap.put("authorizeState", "授权失败");
                                                    updateShopMap.put("sellerId", item.getSellerId());
                                                    updateShopMap.put("regionGuid", item.getRegionGuid());
                                                    amazonShopMapper.updateByAuthorizeState(updateShopMap);
                                                }
                                                apiLogService.updateApiLog(insertLogId, system, type, "亚马逊单个店铺["+ item.getShopUser()  + "-" + item.getShopName() + "]授权失效",item.getShopName() + "ECP_API调用订单实时数据判断是否失效，错误信息为：" + ex.getMessage(),400,"ECP_API调用获取亚马逊单个店铺["+item.getShopName()+"]授权错误，错误信息为："+ex.getMessage());
                                            }
                                        }
                                    }
                                    THREAD_MAP.put(e.getKey(), 0);
                                });
                                t.start();
                                Thread.sleep(2000L);
                            }
                            variable = false;
                            break;
                        }
                    }
                }
            }else {
                apiResponse.setMessage("运营商名下店铺信息为空，不判断店铺失效！");
            }
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用订单实时数据判断是否失效出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API调用订单实时数据判断是否失效出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }

    private Date isDaylightSavings(Date date,Integer type){
        //美国以纽约时区为例/英国以伦敦为例
        String enumS = "";
        if (type == 0){
            enumS = "Europe/London";
        } else {
            enumS = "America/Tijuana";
        }
        ZoneId zoneId = ZoneId.of(enumS);
        //获取当前时区当前时间
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), zone);
        //获取时区计时规则
        ZoneRules rules = zoneId.getRules();
        //true表示处于夏令时，否则冬令时
        boolean result = rules.isDaylightSavings(zonedDateTime.toInstant());
        //ture 夏时令 反之冬时令
        int hour = 0;
        if (result){
            if (type == 0){
                hour = 1;
            } else {
                hour = -7;
            }
        }else {
            if (type == 0){
                hour = 0;
            } else {
                hour = -8;
            }
        }
        Calendar after_datetime = Calendar.getInstance();
        after_datetime.setTime(date);
        after_datetime.add(Calendar.HOUR, hour);//日期加减
        date = after_datetime.getTime();
        return  date;
    }


    @Override
    public ApiResponse getAmazonAuthUrlGg(Map<String, Object> queryParams) {
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (queryParams == null) {
                apiResponse.setCode(400);
                apiResponse.setMessage("参数queryParams不能为空！");
                return apiResponse;
            }
            String shopId = (String) queryParams.get("shopId");
            String userId = (String) queryParams.get("userId");
            if (StringUtils.isEmpty(shopId) || StringUtils.isEmpty(userId)) {
                apiResponse.setCode(400);
                apiResponse.setMessage("数据参数中shopId与userId不能为空！");
                return apiResponse;
            }
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(shopId);
            if (amazonShop == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("参数中shopId对应的店铺信息不存在！");
                return apiResponse;
            }
            MarketplaceEnum marketplaceEnum = MarketplaceEnum.getEnumByCode(amazonShop.getRegionCode());
            if (marketplaceEnum == null){
                apiResponse.setCode(400);
                apiResponse.setMessage("获取店铺对应的区域枚举出错！");
                return apiResponse;
            }
            String spApiAuthUrl = marketplaceEnum.getCpcAuthUrl();

            spApiAuthUrl = spApiAuthUrl + String.format(ApiConfig.getAmazonAdsApiAuthUrl(), ApiConfig.getAmazonClientId(),ApiConfig.getAmazonRedirectUri(),amazonShop.getGuid());
            apiResponse.setSuccess(true);
            apiResponse.setCode(0);
            apiResponse.setExtendAttr(spApiAuthUrl);
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API生成亚马逊广告授权URL地址出错，具体错误信息为："+ex.getMessage());
            logger.error("ECP_API生成亚马逊广告授权URL地址出错，错误信息为：" + ex.getMessage());
        }
        return  apiResponse;
    }
}
